package com.research.web.config.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.research.web.config.properties.ServiceConfig;
import com.research.web.entity.ServiceBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class DataSourceConfig {
    @Autowired
    private ServiceConfig serviceConfig;

    @Bean("dataSourceList")
    @RefreshScope
    public List<DruidDataSource> initDataSource() {
        return getDataSourceList(serviceConfig);
    }

    public static List<DruidDataSource> getDataSourceList(ServiceConfig serviceConfig) {
        List<ServiceBean> list = serviceConfig.getList();
        if (ObjectUtils.isEmpty(list)) {
            return null;
        }
        List<DruidDataSource> result = new ArrayList<>(list.size());
        for (ServiceBean serviceBean : list) {
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setName(serviceBean.getId());
            dataSource.setDriverClassName(serviceBean.getDriverClassName());//如果不配置druid会根据url自动识别dbType，然后选择相应的driverClassName
            dataSource.setUrl(serviceBean.getUrl());
            dataSource.setUsername(serviceBean.getUsername());
            dataSource.setPassword(serviceBean.getPassword());
            dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效
            dataSource.setTestOnBorrow(false);//借用连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能
            dataSource.setTestOnReturn(false);//归还连接时执行validationQuery检测连接是否有效，做了这个配置会降低性能
            //连接空闲时检测，如果连接空闲时间大于timeBetweenEvictionRunsMillis指定的毫秒，执行validationQuery指定的SQL来检测连接是否有效
            dataSource.setTestWhileIdle(true);//如果检测失败，则连接将被从池中去除
            dataSource.setTimeBetweenEvictionRunsMillis(60000);//1分钟
            dataSource.setMaxActive(20);
            dataSource.setInitialSize(5);
            result.add(dataSource);
        }
        return result;
    }
}
